package com.test.gae;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;


import Database.Episode;
import Database.Film;
import Database.UserData;
import Database.UserFilm;

public class DBManager {
	
	private static final Logger log = Logger.getLogger(ProtocolParser.class
			.getName());	
	
	public String saveUser(String username, String password) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + UserData.class.getName()+" where username=="+username;
	    List<UserData> users = (List<UserData>) pm.newQuery(query).execute();
	    if (!users.isEmpty()){
	    	//уже зареган с таким логином
	    	log.info("User "+username+" already registered!");
	    	return "error";
	    }
		try {
            pm.makePersistent(new UserData(username,password));
            log.info("Successfully created user in DB: "+username);
        } finally {
            pm.close();
        }
        return "ok";    
	}

	public String saveUserEpisode(String username, long episodeID) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		//Проверим, есть ли такой эпизод в базе
		String query = "select from " + Episode.class.getName()+" where episodeID=="+episodeID;
		List<Episode> episodes = (List<Episode>) pm.newQuery(query).execute();
		if (episodes.isEmpty()){
			log.info("No episode foiund by ID="+episodeID);
			return "no such episode";
		}
		//Проверим, не смотрел ли уже его юзер
		String query2 = "select from " + UserFilm.class.getName()+" where username=="+username+" && episodeID=="+episodeID;
		  
	    List<UserFilm> users = (List<UserFilm>) pm.newQuery(query2).execute();
	    if (!users.isEmpty()){
	    	//уже смотрел
	    	log.info("User "+username+" already watched episode with ID="+episodeID);
	    	return "duplicate";
	    }
		try {
            pm.makePersistent(new UserFilm(username,episodeID));
            log.info("Successfully added episode with ID="+episodeID+" to user "+username+" in DB");
        } finally {
            pm.close();
        }
        return "ok"; 
	}

	public String saveUserFilm(String username, long filmID) {
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		//Проверим, есть ли такой фильм в базе
		String query = "select from " + Film.class.getName()+" where filmID=="+filmID;
		List<Film> films = (List<Film>) pm.newQuery(query).execute();
		if (films.isEmpty()){
			log.info("No film found by ID="+filmID);
			return "no such film";
		}
		//Проверим, не смотрел ли уже его юзер
		String query2 = "select from " + UserFilm.class.getName()+" where username=="+username+" && filmID=="+filmID;
		  
	    List<UserFilm> users = (List<UserFilm>) pm.newQuery(query2).execute();
	    if (!users.isEmpty()){
	    	//уже смотрел
	    	log.info("User "+username+" already watched film with ID="+filmID);
	    	return "duplicate";
	    }
		try {
            pm.makePersistent(new UserFilm(username,filmID));
            log.info("Successfully added episode with ID="+filmID+" to user "+username+" in DB");
        } finally {
            pm.close();
        }
        return "ok"; 
	}
    
}

